package com.example.lock.独占锁;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Cache {

    private volatile Map<String,Object> map = new HashMap<>();

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();//读写锁

    public void put(String key,String value){
        System.out.println(Thread.currentThread().getName()+"\t *************："+key);
        readWriteLock.writeLock().lock();
        try {
            //readWriteLock.writeLock().tryLock(10,TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName()+"\t 正在写入key："+key);
            TimeUnit.MILLISECONDS.sleep(300);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t 写入完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"\t ===================："+key);
        readWriteLock.readLock().lock();
        try {
            //readWriteLock.readLock().tryLock(10,TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName()+"\t 正在读取key："+key);
            TimeUnit.MILLISECONDS.sleep(300);
            Object result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 读取完成："+result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

}
